package com.beiding.natgo.client;

import com.beiding.natgo.common.Message;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.util.Timer;
import java.util.TimerTask;

@Slf4j
public class SessionManager {

    //只持有一个Session
    private SessionHolder sessionHolder;

    private Timer hearTimer;

    public void handleMessage(Session session, Message message) {

        if (message.getType() == 1) {

       /*     System.out.println("客户端消息内容========");
            System.out.println(new String(message.byteData()));
            System.out.println("==========");
        */
            sessionHolder.writeData(message.getChanelId(), message.byteData());
        } else if (message.getType() == 3) {//初始化端口失败

            try {
                log.info("服务器端初始化端口失败");
                log.info(message.getMsg());
                Thread.sleep(2000);
                log.info("重试初始化端口");
                sessionHolder.sendInitPort();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } else if (message.getType() == 4) {//创建新连接
            sessionHolder.createChanel(message.getChanelId());
        } else if (message.getType() == 7) {//关闭通道
            sessionHolder.closeChanel(message.getChanelId());
        } else if (message.getType() == 6) {//对方错误
            log.info("服务端错误");
            log.info(message.getMsg());
        } else if (message.getType() == 9) {
            log.info("端口初始化成功");
        }
    }

    public void intSession(Session session, ClientConfig config) {
        this.sessionHolder = new SessionHolder(session);
        this.sessionHolder.setClientConfig(config);
        this.sessionHolder.startClientWorker();
    }

    public void remove(Session session) {//

    }

    public SessionHolder getSessionHolder() {
        return sessionHolder;
    }

    public void start() {
        hearTimer = new Timer();
        hearTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    log.info("发送心跳包");
                    sessionHolder.sendHeart();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 10 * 1000);
    }

    public void stop() {
        try {
            hearTimer.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}